<template>
    <view>
        <view
            class="j-video-box" id="videoBox"
            :style="{height: height + 'px'}"
            @click="showControl"
            @longpress="longPress(2)"
            @touchend="touchend(2)"
        >
            <uni-transition
                ref="ani"
                custom-class="transition"
                :mode-class="modeClass"
                :styles="styles"
                :show="show"
                @change="onChange"
            >
                <!--                :style="{height: height + 'px'}"-->
                <video
                    class="j-video"
                    ref="videoName"
                    :controls="false"
                    :autoplay="autoplay"
                    :show-progress="controls"
                    :loop="loop"
                    :muted="muted"
                    id="video"
                    object-fit="contain"
                    :style="{
                        height: fullScreen? height + 'px': '300px'
                    }"
                    :src="src"
                    @loadedmetadata="getVideoInfo"
                    @timeupdate="timeUpdate"
                    @fullscreenchange="screenChange"
                    @longpress.stop="longPress(1)"
                    @touchend.stop="touchend(1)"
                    @ended="ended"
                    @play="()=>{this.playStatus=0}"
                    @pause="()=>{this.playStatus=1}"
                >
                </video>
            </uni-transition>
            <view v-if="longTouch" class="play-rate">
<!--                <image></image>-->
                <text style="color: #FF0025;">2.0 倍速</text>
                <text style="color: #FFFFFF">快进中</text>
            </view>
            <view
                class="j-video-handle"
                v-if="handle"
                style="z-index: 99999"
            >
                <view class="handle-top">
                    <view class="play">
                        <image
                            v-if="playStatus === 1"
                            src="https://statics.xmcsrv.net/weixin/play2-1.png"
                            style="width: 20px;height: 20px;"
                            @click.stop="playFn(0)"
                        ></image>
                        <image
                            v-else
                            src="https://statics.xmcsrv.net/weixin/pause2-1.png"
                            style="width: 20px;height: 20px;"
                            @click.stop="playFn(1)"
                        ></image>
                    </view>
                    <view class="muted" @click.stop="mutedChange">
                        <image v-if="muted" src="https://statics.xmcsrv.net/weixin/mute0-0.png" style="width: 100%;height:100%"></image>
                        <image v-else src="https://statics.xmcsrv.net/weixin/mute0-1.png" style="width: 100%;height:100%"></image>
                    </view>
                    <view class="camera" @click.stop="screenShot">
                        <image src="https://statics.xmcsrv.net/weixin/camera.png" style="width: 100%;height:100%"></image>
                    </view>
                    <view class="full-screen">
                        <!--                    全屏-->
                        <i
                            v-if="fullScreen === false"
                            class="icon iconfont icon-fullscreen"
                            style="color: #fff; font-size: 22px;"
                            @click.stop="fullScreenFn(true)"
                        ></i>
                        <i
                            v-if="fullScreen === true"
                            class="icon iconfont icon-tuichuquanping-02"
                            style="color: #fff; font-size: 22px;"
                            @click.stop="fullScreenFn(false)"
                        ></i>
                    </view>
                </view>
                <view class="handle-bottom">
                    <view class="progress">
                        <text class="start">{{ currentTime }}</text>
                        <view class="pro-control" @click.stop="" @longpress.stop="">
                            <slider
                                :value="value"
                                :stroke-width="2"
                                active-color="#fff"
                                background-color="#ccc"
                                :active="true"
                                :block-size="12"
                                @change="change"
                                @changing="changing"
                            ></slider>
                        </view>
                        <text class="end">{{setSecond}}</text>
                    </view>
                </view>
            </view>
            <view class="center-box" v-if="playStatus === 1" @click.stop="playFn(0)">
                <image
                    style="width: 100%; height: 100%"
                    src="https://statics.xmcsrv.net/weixin/replay.png"
                ></image>
            </view>
            <view class="canvas-box" v-show="cvs">
                <view>
                    <canvas style="opacity: 0;" :style="{width:Artwidth+ 'rpx',height:Artheight + 'rpx',transform: 'scale('+1/dpr+')'}" class="canvas" type="2d" id="cvs1" canvas-id="cvs1"></canvas>
                </view>
                <view class="text-cvs">
                    <!-- <text>哇,拍到一张美照!</text> -->
                </view>
            </view>
            <!--<canvas v-if="cvs" class="canvas-box" type="2d" id="cvs1" canvas-id="cvs1"></canvas>-->
        </view>

        <!--<button @click="handleFn(0)">缩小</button>-->
        <!--<button @click="handleFn(1)">放大</button>-->
    </view>
</template>

<script>
import {isDoorLock} from "@/utils/util";

export default {
    name: 'JVideo',
    props: {
        width: {
            type: [Number, String],
            default: 300
        },
        height: {
            type: [Number, String],
            default: 225
        },
        src: {
            type: String,
            default: ''
        },
        autoplay: {
            type: Boolean,
            default: true
        },
        loop: {
            type: Boolean,
            default: true
        },
        scale: {
            type: Array,
            default: [1, 1]
        },
    },
    onLoad() {
        this.styles = {
            justifyContent: 'center',
            alignItems: 'center',
            // width: '100vw',
            height: '300px',
            borderRadius: '5px',
            textAlign: 'center',
            backgroundColor: '#4cd964',
            boxShadow: '0 0 5px 1px rgba(0,0,0,0.2)'
        }
        this.scaleH = [...this.scale]
    },
    onShow() {
        // console.log(this.width, this.height)
    },
    onReady(res) {
        // 获取视频组件信息
        this.videoContext = uni.createVideoContext('video', this)
        this.doorType = this.$parent.device.parentPid
        console.log(this.doorType)

        // console.log('视频组件信息', this.videoContext)
        // this.$nextTick(() => {
        //     this.showControl()
        // })

        // // 获取元素位置
        // setTimeout(() => {
        //     wx.createSelectorQuery().select('.j-video').context(result => {
        //         console.log('select video1', result.context)
        //         this.video = result
        //     })
        //     const video = uni.createSelectorQuery().select('#video').context
        //     console.log(this.video, 'video元素信息2')
        //     console.log(video, 'video元素信息')
        // }, 1000)

    },
    watch: {
        width: {
            handler(n, o) {
                // console.log(n)
            },
            immediate: true,
            deep: true
        },
        height: {
            handler(n, o) {
                // console.log(n, 'HEIGHT变化了')
                const rate = (n/300)
                this.scaleH[0] = rate
                this.scaleH[1] = rate
                // console.log(rate)
                // console.log(this.scale)
            },
            immediate: true,
            deep: true
        },
        src: {
            handler(n, o) {
                this.showControl('',true)
                this.playStatus = 0
                this.muted = true
            },
            immediate: true,
            deep: true
        }
    },
    data() {
        return {
            fullScreenH: '',
            longTouch: false,
            video: null ,
            playStatus: 0,  // 播放状态 0：暂停，1：播放
            muted: true,  // 静音
            styles: {},
            show: true,
            modeClass: 'fade',
            scaleH: [1, 1],
            src2: 'https://vd4.bdstatic.com/mda-mhmccajvqqq6fs83/sc/cae_h264/1629622455645825022/mda-mhmccajvqqq6fs83.mp4?v_from_s=hkapp-haokan-nanjing&auth_key=1692263720-0-0-a7b1d1c05d6e362f6e3056518795ac00&bcevod_channel=searchbox_feed&pd=1&cr=2&cd=0&pt=3&logid=0919924135&vid=14005544185206936375&klogid=0919924135&abtest=111803_3',
            fullScreen: false,
            videoContext: null,
            videoAttr: {
                width: 0,
                height: 0,
                duration: 0,
            },
            currentTime: '00:00',
            value: 0,
            controls: false,
            handle: false,
            handleTimer: null,
            status: true, // true 放大 false 缩小
            cvs: false,
            doorType: '',
            changingStatus: false,
			Artwidth: 0,
			Artheight: 0,
			dpr:0
        }
    },
    computed: {
        setSecond() {
            const val = this.videoAttr.duration
            return this.setTimeFn(val)
        },
    },
    methods: {
        change(e) {
            this.changingStatus = true
            clearTimeout(this.handleTimer)
            this.videoContext.seek(e.detail.value / 100 * this.videoAttr.duration)
            this.playFn(0)
            this.changingStatus = false
            this.handleTimer = setTimeout(() => {
                this.handle = false
            }, 4000)
        },
        changing(e) {
            clearTimeout(this.handleTimer)
            this.changingStatus = true
        },
        bindLoadedMetaData(e) {
            setTimeout(() => {
                // this.draw(1, false, false)
				this.beginDrawImg(1, false, false)
            }, 500)
        },
        escScreen() {
            this.$emit('escScreen')
        },
        fillScreenFn() {
            this.$emit('fullscreen')
        },
        touchend(i) {
            this.longTouch = false
            this.videoContext.playbackRate(1)
            console.log(this.handle)
            clearTimeout(this.handleTimer)
            this.handleTimer = setTimeout(() => {
                this.handle = false
            }, 4000)
        },
        // 长按
        longPress(i) {
            clearTimeout(this.handleTimer)
            if(this.playStatus === 0) {
                this.longTouch = true
                this.videoContext.playbackRate(2)
            }
        },
        // 判断是否是门锁
        isDoorLockFn() {
            const arr = isDoorLock()
            const list = arr.filter(item => item === this.doorType)
            console.log(list)
            if(list.length) {
                // 是门锁
                return true
            } else {
                // bushi
                return false
            }
        },
        ended(e) {
            // console.log("播放结束了", e)
            this.playFn(1)
            // this.cvs = false
        },
        draw(status = 0, save = true, click = true) {
            let that = this
            const dpr = wx.getSystemInfoSync().pixelRatio
            console.log(dpr)
            this.createSelectorQuery().select('#video').context(res => {
                this.video = null
                // console.log('select video', res)
                this.video = res.context
            }).exec((res) => {
            })
            this.createSelectorQuery().selectAll('#cvs1').node(res => {
                // console.log('select canvas', res)
                console.log('canvas node', res[0].node)
                const ctx1 = res[0].node.getContext('2d')

                console.log(this.video, 'this.video');
                let widthDPR, heightDPR
                if(this.isDoorLockFn()) {
                    widthDPR = 720
                    heightDPR = 1280
                    if(this.doorType === 'HAVLS00100001009') {
                        // 650设备自定义分辨率
                        widthDPR = this.videoAttr.width
                        heightDPR = this.videoAttr.height
                    }
                } else {
                    widthDPR = 300 * dpr
                    heightDPR = 200 * dpr
                }
                res[0].node.width = widthDPR
                res[0].node.height = heightDPR
                this.$nextTick(() => {
                    ctx1.drawImage(this.video, 0, 0, widthDPR, heightDPR)
                })
                if(!status) {
                    if(save) {
                        setTimeout(() => {
                            let tempFilePath = ''
                            wx.canvasToTempFilePath({
                                x: 0,
                                y: 0,
                                canvas: res[0].node,
                                success: function (res) {
                                    console.log(res.tempFilePath);
                                    tempFilePath = res.tempFilePath
                                    wx.saveImageToPhotosAlbum({
                                        filePath: tempFilePath,
                                        success: (res) => {
                                            console.log('下载成功')
                                        },
                                        fail: (err) => {
                                            console.log('下载失败');
                                        }
                                    })
                                },
                                fail: (err) => {
                                    console.log(err, '下载失败');
                                }

                            })
                        }, )
                    }
                } else {
                    setTimeout(() => {
                        this.draw(0, false, false)
                    }, 1000)
                }

                // setInterval(() => {
                //     ctx1.drawImage(this.video, 0, 0, 300 * dpr, 200 * dpr);
                // }, 1000 / 24)
            }).exec((res) => {

            })
        },
        
		beginDrawImg(status = 0, save = true) {
			let dpr = wx.getSystemInfoSync().pixelRatio || 1;
			this.dpr = dpr
			let widthDPR, heightDPR
			console.log(this.videoAttr,'this.videoAttr')
			if(this.videoAttr.width > this.videoAttr.height){
				widthDPR = this.videoAttr.width
				heightDPR = this.videoAttr.height
			}else{
				widthDPR = 720
				heightDPR = 1280
			}
			const query = uni.createSelectorQuery().in(this)
			query.select('#video').context(res => {
				this.video = res.context
			}).exec((res) => {})
			this.DrawImg(status, save,'#cvs1', 0, 0, widthDPR, heightDPR, dpr)
		},
		//canvas的ID名、绘制的x位置，绘制的y位置，绘制的宽，绘制的高，清晰的倍数
		DrawImg(status, save, CVID, x, y, w, h, dpr) {
			if(this.cvs){
				uni.showLoading()
			}
			let that = this
			const query = uni.createSelectorQuery().in(this)
			console.log(this.video)
			query.select(CVID).fields({
				node: true,
				size: true
			}).exec(res => {
				console.log(res, 'fields')
				const {
					node: canvas
				} = res[0];
				console.log(canvas)
				const ctx = canvas.getContext('2d');
				const dataInfo = that.scaleValue(x, y, w, h, dpr)
				dataInfo.then((res) => {
					console.log(res)
					canvas.width = res.w
					canvas.height = res.h
					//看的见的画布大小，按实际需求赋值
					that.Artwidth = w
					that.Artheight = h
		
					ctx.drawImage(this.video, 0, 0, canvas.width, canvas.height)
					//然后将当前绘图放大，切记理解这个，不是放大画布，而是放大你的绘图内容
					ctx.scale(dpr, dpr);
					if(!status) {
					    if(save) {
							setTimeout(() => {
								let tempFilePath = ''
								wx.canvasToTempFilePath({
									x: 0,
									y: 0,
									canvas: canvas,
									success: function(res) {
										uni.hideLoading()
										tempFilePath = res.tempFilePath
										wx.saveImageToPhotosAlbum({
											filePath: tempFilePath,
											success: (res) => {
												console.log('下载成功');
												uni.showToast({
													title:'截图成功',
													icon:"none"
												})
											},
											fail: (err) => {
												uni.showToast({
													title:'截图失败，请重试',
													icon:"none"
												})
												console.log('下载失败');
											}
										})
									},
									fail: (err) => {
										uni.hideLoading()
										console.log(err, '下载失败');
										this.$logs({
											info: '截图失败',
											err: err,
											functionName:'canvasToTempFilePath'
										})
									}
									
								})
							})
					    }
					} else {
					    setTimeout(() => {
					        // this.draw(0, false, false)
							this.beginDrawImg(0, false, false)
					    }, 1000)
					}
				}, (err) => {})
			})
		},
		//同比放大绘制的内容，目的为了高清
		scaleValue(x, y, w, h, dpr) {
			return new Promise((resolve, reject) => {
				const data = {
					x: x * dpr,
					y: y * dpr,
					w: w * dpr,
					h: h * dpr,
				}
				if(data.h > 4090){
					data.h = 4000;
					data.w = 2250
				}
				resolve(data)
			})
		},
		// 截图
        screenShot() {
            if(this.playStatus === 1) {
                uni.showToast({
                    title: '需要在视频播放状态下，才能操作...',
                    icon: 'none'
                })
                return
            }
            this.cvs = true;
			console.log('点击截图')
            // this.draw();
			this.beginDrawImg()
            setTimeout(() => {
                this.cvs = false
            }, 100000)
        },
        // 静音
        mutedChange() {
            if(this.muted) {
                // 当前是静音，转换去非静音
                console.log('当前是静音，转换去非静音')
            } else {
                // 静音
                console.log('静音')
            }
            this.muted = !this.muted
        },
        // 显示自定义控制框
        showControl(e, s) {
            if(s) {
                this.handle = s
                clearTimeout(this.handleTimer)
                this.handleTimer = setTimeout(() => {
                    this.handle = false
                }, 4000)
                return
            }
            // 在加载时执行一次
            if(!this.handle) {
                this.handle = true
                clearTimeout(this.handleTimer)
                this.handleTimer = setTimeout(() => {
                    this.handle = false
                }, 4000)
            } else {
                this.handle = false
                clearTimeout(this.handleTimer)
            }
        },
        //
        timerControl() {
            if(this.handleTimer) {
                clearTimeout(this.handleTimer)
                console.log(this.handleTimer)
                this.handleTimer = setTimeout(() => {
                    this.handle = false
                }, 4000)
            }
        },
        // 全屏
        screenChange(e) {
            // this.timerControl()
            // console.log(e)
            if(!e.detail.fullScreen) {
                this.fullScreenFn(false)
            } else {
                this.fullScreen = false
                this.fullScreenH = '300px'
                this.controls = false
                this.$parent.navHeightChange(0)
            }
            // this.timerControl()
        },
        // 时间处理函数
        setTimeFn(val) {
            let time = Math.floor(val)
            let h = Math.floor(val/60)
            let s = time - h * 60
            let str = ''
            if(h<10) {
                str = str + '0' + h + ':'
            } else {
                str = str + h + ''
            }
            if(s<10) {
                str = str + '0' + s
            } else {
                str = str + s
            }
            // console.log(str, '变化后的时间')
            return str
        },
        // 播放进度变化的回调
        timeUpdate(e) {
            // console.log(e, '播放进度变化的回调')
            if(!this.changingStatus) {
                // 没有手动滑动控制条
                const time = e.detail.currentTime
                this.currentTime = this.setTimeFn(time)
                this.value = time/this.videoAttr.duration*100
                // console.log(this.value, '进度条变动')
            } else {
                // 手动控制控制条
                // console.log('手动控制')
                clearTimeout(this.handleTimer)
            }
        },
        // 获取视频信息
        getVideoInfo(e) {
            // width 视频宽度 height 视频高度 duration 视频长短  xx秒
            this.videoAttr = e.detail
            this.bindLoadedMetaData()
            // console.log('视频信息', e.detail)
        },
        // 点击播放事件
        playFn(status) {
            this.playStatus = status
            // 调用相关播放器播放，暂停事件。 0 暂停要播放 1 播放要暂停
            if(status) {
                this.videoContext.pause()
            } else {
                this.videoContext.play()
            }
            // this.timerControl()
        },
        fullScreenFn(handle) {
            // 全屏
            if(handle) {
                this.fullScreenH = this.height + 'px'
                this.fullScreen = true
                this.controls = true
                this.longTouch = false
                this.videoContext.playbackRate(1)
                this.fillScreenFn()
                // this.$nextTick(() => {
                //     if(this.status) {
                //         setTimeout(() => {
                //             this.$parent.navHeightChange(1)
                //         })
                //     }
                //     this.videoContext.requestFullScreen()
                // })
            } else {
                // 退出全屏
                this.fullScreenH = '300px'
                this.fullScreen = false
                this.controls = false
                this.escScreen()
                // console.log('退出全屏123')
                this.$parent.navHeightChange(0)
            }
            // this.timerControl()
        },
        // 缩小放大
        handleFn(status) {
            if(status === 0) {
                // 缩小
                this.status = false
                // console.log(this.scaleH, '1232345234')
                const scale = [...this.scaleH]
                // console.log(scale)
                this.$refs.ani.step({
                    scale: this.scale
                },{
                    duration: 600,
                    timingFunction:'ease',
                    // delay:200,
                    transformOrigin:'center, top'
                })
                const videoBox = uni.createSelectorQuery().select("#videoBox")
                // console.log(videoBox)

            } else if (status === 1) {
                // 放大
                this.status = true
                this.scaleH = [1, 1]
                this.$refs.ani.step({
                    scale: [1, 1]
                },{
                    duration: 600,
                    timingFunction:'ease',
                    delay: 200,
                    transformOrigin:'center, top'
                })
                // this.$refs.videoBox.style.height = 300 * 1 + 'px'
            }
            this.$refs.ani.run()
            this.timerControl()
        },
        onChange(e) {
            // console.log(e)
        }
    }
}
</script>

<style lang="scss" scoped>
* {
    margin: 0;
    padding: 0;
}
.j-video-box {
    width: 100%;
    background-color: #020202;
    height: 100%;
    //background-color: #ccc;
    margin: 0;
    padding: 0;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    flex-direction: column;
    transition: all 0.8s;
    //transition-delay: 0.2s;
}
.j-video {
    width: 100vw;
    height: 300px;
}
.right-box {
    position: absolute;
    width: 30px;
    height: 100px;
    right: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    view {
        width: 44rpx;
        height: 44rpx;
        //background-color: #ccc;
        //opacity: 0.6;
        display: flex;
        justify-content: center;
        align-items: center;
    }
}
.j-video-handle {
    position: absolute;
    bottom: 0;
    width: 100%;
    //height: 20px;
    //background-color: #f40;
    padding-top: 8px;
    opacity: 1;
    display: flex;
    flex-direction: column;
	align-items: center;
    transition: all 0.5s;
    border-radius: 5px 5px 0 0;
    background-color: rgba(0,0,0,.6);
    .handle-top {
        width: 80%;
        height: 20px;
        display: flex;
        justify-content: space-around;
        align-items: center;
        .play {
            display: flex;
            justify-content: center;
            align-items: center;
            //margin-left: 32rpx;
            width: 25px;
            height: 25px;
        }
        .camera {
            display: flex;
            justify-content: center;
            align-items: center;
            //margin-left: 32rpx;
            width: 25px;
            height: 25px;
        }
        .muted {
            width: 25px;
            height: 25px;
            color: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
            //margin-left: 20rpx;
        }
        .full-screen {
            //margin-right: 28rpx;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }
    .handle-bottom {
        width: 100%;
        .progress {
            flex: 1;
            padding: 0 20px;
            //background-color: #adf;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 14px;
            .start {
                width: 42px;
                color: #fff;
            }
            .pro-control {
                flex: 1;
            }
            .end {
                margin-left: 5px;
                display: flex;
                width: 30px;
                color: #fff;
            }
        }
    }
}
.canvas-box {
    position: absolute;
    bottom: 30%;
    left: 50%;
    transform: translate(-50%, 0);
}
.canvas {
    width: 100px;
    height: 75px;
}
.text-cvs {
    color: #fff;
    font-size: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.center-box {
    width: 100rpx;
    height: 100rpx;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    //background-color: #fff;
}
.play-rate {
    z-index: 100000001;
    position: absolute;
    width: 100px;
    height: 20px;
    background-color: rgba(0,0,0,.6);
    border-radius: 5px;
    padding: 3px;
    top: 20%;
    font-size: 12px;
    display: flex;
    justify-content: space-around;
    align-items: center;
}
</style>